﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GoogleSchemeTileLoader
{
    public class TileTool
    {

        /// <summary>
        /// 生成缓存切片
        /// </summary>
        /// <param name="path">切片所在文件夹路径</param>
        /// <param name="z">缩放级别</param>
        public static void ConfigAndCreateTile(string path,int z)
        {

            //切片原点
            double webMectorMinX = -20037508.342789244;
            double webMectorMinY = -20048966.1040146;

            //区域范围
            double minX = -20026376.39;
            double minY = -20048966.10;
            double maxX = 20026376.39;
            double maxY = 20048966.10;

            int tileSize = 256;
            List<Scheme> schemes = Scheme.getGoogleScheme();
            double resolution = schemes[z].Resolution;
            int minCol = XytoColRow.getCol(webMectorMinX, minX, tileSize, resolution);
            int maxCol = XytoColRow.getCol(webMectorMinX, maxX, tileSize, resolution);
            int minRow = XytoColRow.getRow(webMectorMinY, minY, tileSize, resolution);
            int maxRow = XytoColRow.getRow(webMectorMinY, maxY, tileSize, resolution);
            Console.WriteLine(minCol);
            Console.WriteLine(maxCol);
            Console.WriteLine(minRow);
            Console.WriteLine(maxRow);

            for (int x = minCol; x <= maxCol; x++)
            {
                for (int y = minRow; y <= maxRow; y++)
                {
                    string url = "https://wayback.maptiles.arcgis.com/arcgis/rest/services/world_imagery/mapserver/tile/" + z + "/" + x + "/" + y + "";
                    TileTool.LoadTile(path,x, y, z, url);
                    Console.WriteLine("已经生成了该" + z + " / " + x + " / " + y + "切片");
                }
            }
            Console.WriteLine("获取完成");

        }


        /// <summary>
        /// 下载切片
        /// </summary>
        /// <param name="path"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        /// <param name="url"></param>
        public static void LoadTile(string path,int x, int y, int z, string url)
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //加上这一句
            TileTool.GreateFile(path, z);
            TileTool.GreateFile(path +z, x);
            string pathName = path + z + @"\" + x + @"\" + y + ".png";
            using (WebClient client = new WebClient() { })
            {
                try
                {
                    client.DownloadFile(url, pathName);
                }
                catch (WebException ex)
                {
                    using (HttpWebResponse hr = (HttpWebResponse)ex.Response)
                    {
                        int statusCode = (int)hr.StatusCode;
                        StringBuilder sb = new StringBuilder();
                        StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8);
                        sb.Append(sr.ReadToEnd());
                        Console.WriteLine("StatusCode:{0},Content:{1}", statusCode, sb);// StatusCode:401,Content:test
                    }
                }

            }

        }


        /// <summary>
        /// 创建新文件
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <param name="fileName"></param>
        public static void GreateFile(string directoryPath, int fileName)
        {
            try
            {
                if (Directory.Exists(directoryPath))
                {
                    DirectoryInfo dir = new DirectoryInfo(directoryPath);
                    dir.CreateSubdirectory(fileName.ToString());
                }
            }
            catch (Exception e)
            {
                return;
            }
            finally { }
        }
    }
}
